<?php

namespace App\Services\System;

use App\Common\Constants\CacheConst;
use App\Exceptions\ApiException;
use App\Models\System\SysUserModel;
use Illuminate\Support\Facades\Cache;
use ruoyi\admin\Utils;

class PasswordService {

    public static function validatePassword(SysUserModel $user, $input_password, $precallback=null) {
        $maxRetryCount = 5; // 密码最大错误次数
        $lockTime = 10; // 密码锁定时间（默认10分钟）   todo 配置
        $rk = CacheConst::PWD_ERR_CNT_KEY() . $user->username;
        $retryCount = intval(Cache::get($rk));
        if ($retryCount >= $maxRetryCount) {
            $msg = sprintf('密码输入错误%s次，帐户锁定%s分钟', $maxRetryCount, $lockTime);
            // SysLogininfor::recordLogininfor($user['username'], Constants::LOGIN_FAIL, $msg);
        } else if (!Utils::matchesPassword($input_password, $user['password'])) {
            // SysLogininfor::recordLogininfor($user['username'], Constants::LOGIN_FAIL, sprintf('密码输入错误%s次', $retryCount));
            Cache::put($rk, $lockTime*60, $retryCount);
            $msg = '用户不存在/密码错误';
        }
        if (isset($msg)) {
            $precallback && $precallback($msg);
            ApiException::throw_str($msg);
        }
        Cache::forget($rk);
    }

}
